﻿using Ast.Framework.FileSystems.Paths;

namespace Ast.Framework.Utility.Extensions
{
    public static class PathProviderExtensions
    {
        public static string GetProjectReferencePath(this IPathProvider pathProvider, string projectPath, string referenceName, string hintPath)
        {
            var basePath = pathProvider.GetDirectoryName(projectPath);
            var path = pathProvider.GetReferencePath(basePath, referenceName, hintPath);

            return !string.IsNullOrEmpty(path)
                ? pathProvider.Combine(basePath, path)
                : null;
        }

        public static string GetReferencePath(this IPathProvider pathProvider, string basePath, string referenceName, string hintPath)
        {
            // Check if hint path is valid
            if (!string.IsNullOrEmpty(hintPath))
            {
                if (pathProvider.FileExists(pathProvider.Combine(basePath, hintPath)))
                    return hintPath;
            }

            // Fall back to bin directory
            var relativePath = pathProvider.Combine("bin", referenceName + ".dll");
            if (pathProvider.FileExists(pathProvider.Combine(basePath, relativePath))) return relativePath;
            relativePath = pathProvider.Combine("bin\\Debug", referenceName + ".dll");
            if (pathProvider.FileExists(pathProvider.Combine(basePath, relativePath))) return relativePath;
            relativePath = pathProvider.Combine("bin\\Release", referenceName + ".dll");
            if (pathProvider.FileExists(pathProvider.Combine(basePath, relativePath))) return relativePath;

            return null;
        }
    }
}